<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/10/18
 * Time: 11:53
 */

namespace app\admin\model;


use think\Db;
use think\Exception;
use think\Model;

class SysPermission extends Model
{
    protected $table = 'sys_permission';
    protected $pk = 'id';

    /**
     * 获取菜单对应的权限组
     *
     * @param $menu_id
     * @return array
     */
    public static function getMenuPermits($menu_id) {
        $sql = <<<SQL
SELECT permission_id FROM sys_permission_menu WHERE menu_id=:menu_id
SQL;
        $list = Db::query($sql, ['menu_id' => $menu_id]);
        return array_column($list,'permission_id');
    }

    /**
     * 保存菜单的权限组
     * @param $menu_id
     * @param array $permits
     * @throws Exception
     */
    public static function saveMenuPermits($menu_id, array $permits) {
        try{
            Db::startTrans();

            $sql = 'DELETE FROM sys_permission_menu WHERE menu_id=:menu_id';
            Db::execute($sql, ['menu_id' => $menu_id]);

            $sql = <<<SQL
INSERT INTO sys_permission_menu (menu_id, permission_id) VALUES (:menu_id, :permission_id)
ON CONFLICT (menu_id, permission_id) DO NOTHING 
SQL;
            foreach ($permits as $permit) {
                Db::execute($sql, ['menu_id' => $menu_id, 'permission_id' => $permit]);
            }

            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }


    }

}